package com.woniuxy.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.RedisConst;
import com.woniuxy.portal.model.entity.Book;
import com.woniuxy.portal.service.BookService;
import com.woniuxy.portal.mapper.BookMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
* @author scott
* @description 针对表【t_book】的数据库操作Service实现
* @createDate 2024-10-15 09:46:43
*/
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
    implements BookService{


    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_LIST, keyGenerator = "keyGenerator")
    public Page<Book> findTopSales(Integer pageNum, Integer pageSize) {

        //01 封装分页数据
        Page<Book> page = new Page<>(pageNum, pageSize);

        //02 查询
        // 条件查询 购买量排序
        LambdaQueryWrapper<Book> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //排序
        lambdaQueryWrapper.orderByDesc(Book::getBuyCount);

        Page<Book> bookPage = page(page, lambdaQueryWrapper);

        return bookPage;
    }

    /**
     * 按书籍的类型查询书籍，并且分页，按更新时间降序排序
     * @param pageNum
     * @param pageSize
     * @param typeId
     * @return
     *   cacheNames + "arg[0]"   book::1
     *   cacheNames + keyGenerator(自定义缓存的名称)   book::1
     *        com.woniuxy.portal.BookServiceImpl::findByType::1
     */
    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_LIST, keyGenerator = "keyGenerator")
    public Page<Book> findByType(Integer pageNum, Integer pageSize, Integer typeId) {

        //01 封装分页数据
        Page<Book> page = new Page<>(pageNum, pageSize);
        //02 查询
        // 条件查询 购买量排序
        LambdaQueryWrapper<Book> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //通过类型查询
        lambdaQueryWrapper.eq(!ObjectUtils.isEmpty(typeId), Book::getTypeId, typeId);

        //更新时间降序排序
        lambdaQueryWrapper.orderByDesc(Book::getUpdateTime);

        Page<Book> bookPage = page(page, lambdaQueryWrapper);

        return bookPage;
    }


    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_DETAIL, keyGenerator = "keyGenerator")
    public Book findById(Long id) {
        return getById(id);
    }

}




